package com.none.web.service.like.impl;


import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.none.core.common.utils.CreateID;
import com.none.core.common.utils.StringUtil;
import com.none.core.exception.ValidateException;
import com.none.core.service.BaseServiceSupport;
import com.none.web.model.TLike;
import com.none.web.service.like.ILikeService;

/**
 * 
 * @Description: 点赞管理Service实现
 * @author Bing
 * @date 2015年6月25日 上午10:28:53
 */
@Service("likeService")
public class LikeServiceImpl extends BaseServiceSupport implements ILikeService {
	@Autowired
    JdbcTemplate jdbcTemplate;
	
	@Override
	public Object saveLikeInfo(TLike like, String type,String userId)
			throws Exception {
		if(like==null){
			throw new ValidateException("news.unExist");
		}
		Integer likeNum = this.getLikeNums(like.getContentId(), userId, type);
		if(likeNum>0){
			throw new ValidateException("like.Exist");
		}
		like.setId(CreateID.getID());
		like.setType(type);
		like.setLike_time(new Timestamp(new Date().getTime()));
		like.setUserId(userId);
		like.setDelete_flag("0");
		// 保存
		if (saveEntity(like) == null) {
			throw new ValidateException("common.illegalRequest");
		} else {
			return like;
		}
	}
	@Override
	public Object deleteLikeInfo(String videoId,String type, String userId)
			throws Exception {
		if (StringUtils.isBlank(userId))
			throw new ValidateException("user.userUnExist");
		if("activity".equals(type)){
			//return jdbcTemplate.update("delete from t_like where type=? and contentId=? and userId=?", new Object[]{type,videoId,userId});
			return jdbcTemplate.update("update  t_like set delete_flag=? where type=? and contentId=? and userId=?", new Object[]{"1",type,videoId,userId});
		}else{
			//return jdbcTemplate.update("delete from t_like where contentId=? and userId=?", new Object[]{videoId,userId});
			return jdbcTemplate.update("update  t_like set delete_flag=? where contentId=? and userId=?", new Object[]{"1",videoId,userId});
		}
		
	}
	
	/**
	 * 查看是否点赞
	 * @return
	 */
	private Integer getLikeNums(String contentId,String userId,String type){
		String sql="select count(t.id) num from t_like t where t.delete_flag='0' and  t.contentId='"+contentId+"' and t.userId='"+userId+"' and t.type='"+type+"'";
		Integer num=0;
		List<Map<String, Object>> listMap=this.jdbcTemplate.queryForList(sql);
		num=Integer.valueOf(StringUtil.toStringNumber(listMap.get(0).get("num")));
		return num;
	}
}
